import pymysql
import json
import threading
import time
import logging
from datetime import datetime
from app import db
from app.models.sync_log import SyncLog, SyncLogDetail
from app.models.datasource import DataSource
from app.models.alert import Alert
from app.services.fake_data_service import generate_fake_data
from config import Config

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(f"{Config.LOG_DIR}/sync_service.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

# 存储正在运行的任务
running_tasks = {}

def start_sync_task(task):
    """启动同步任务"""
    try:
        # 检查任务是否已经在运行
        if task.id in running_tasks:
            return False, "任务已经在运行"
        
        # 获取源数据源和目标数据源
        source = DataSource.query.get(task.source_id)
        target = DataSource.query.get(task.target_id)
        
        if not source or not target:
            return False, "数据源不存在"
        
        # 创建同步日志
        sync_log = SyncLog(task_id=task.id)
        db.session.add(sync_log)
        db.session.commit()
        
        # 根据同步类型启动不同的同步线程
        if task.sync_type == 'full':
            # 全量同步
            thread = threading.Thread(
                target=full_sync,
                args=(task, source, target, sync_log)
            )
            thread.daemon = True
            thread.start()
            running_tasks[task.id] = {
                'thread': thread,
                'log_id': sync_log.id,
                'stop_flag': False
            }
        elif task.sync_type == 'incremental':
            # 增量同步
            if not task.incremental_field:
                db.session.delete(sync_log)
                db.session.commit()
                return False, "增量同步需要指定增量字段"
            
            thread = threading.Thread(
                target=incremental_sync,
                args=(task, source, target, sync_log)
            )
            thread.daemon = True
            thread.start()
            running_tasks[task.id] = {
                'thread': thread,
                'log_id': sync_log.id,
                'stop_flag': False
            }
        else:
            db.session.delete(sync_log)
            db.session.commit()
            return False, f"不支持的同步类型: {task.sync_type}"
        
        return True, "任务启动成功"
    except Exception as e:
        logger.error(f"启动同步任务失败: {str(e)}")
        return False, str(e)

def stop_sync_task(task):
    """停止同步任务"""
    try:
        # 检查任务是否在运行
        if task.id not in running_tasks:
            return False, "任务没有在运行"
        
        # 设置停止标志
        running_tasks[task.id]['stop_flag'] = True
        
        # 等待线程结束
        running_tasks[task.id]['thread'].join(timeout=5)
        
        # 如果线程仍在运行，则强制结束
        if running_tasks[task.id]['thread'].is_alive():
            # 无法直接终止线程，但可以更新日志状态
            log_id = running_tasks[task.id]['log_id']
            sync_log = SyncLog.query.get(log_id)
            if sync_log:
                sync_log.status = 'failed'
                sync_log.end_time = datetime.now()
                sync_log.error_message = '任务被强制停止'
                db.session.commit()
        
        # 从运行任务中移除
        del running_tasks[task.id]
        
        return True, "任务停止成功"
    except Exception as e:
        logger.error(f"停止同步任务失败: {str(e)}")
        return False, str(e)

# 导入同步实现
from app.services.sync_implementations import full_sync, incremental_sync